class Node {
  constructor (element) {
    this.element = element
    this.next = null
    this.previous = null
  }
}

class LinkedList {

  constructor () {
    this.head = new Node('head')
  }

  /**
   * 查找指定node
   * @param element
   * @returns {Node}
   */
  find (element) {
    let currNode = this.head
    while (currNode.element !== element) {
      currNode = currNode.next
    }
    return currNode
  }

  /**
   *  找到指定节点前一个节点
   * @param item
   * @returns {Node}
   */
  findPrevious (item) {
    let currNode = this.head
    while ((currNode.next != null) && (currNode.next.element != item)) {
      currNode = currNode.next
    }
    return currNode
  }

  display () {
    let currNode = this.head
    while (currNode.next != null) {
      console.log(currNode.next.element)
      currNode = currNode.next
    }
  }

  /**
   *  在已知节点后面插入
   *  找到已知的节点，将已知节点的下一个节点放到新插入的节点的next
   *  将已知节点的next指向新的节点
   * @param newElement
   * @param item
   */
  insert (newElement, item) {
    let newNode = new Node(newElement)
    let currNode = this.find(item)
    newNode.next = currNode.next
    currNode.next = newNode
    newNode.previous = currNode
  }

  remove (item) {
    // let prevNode = this.findPrevious(item)
    // if (prevNode.next != null) {
    //   prevNode.next = prevNode.next.next
    // }
    let currNode = this.find(item)
    if (currNode.next != null) {
      currNode.next.previous = currNode.previous
    } else if (currNode.previous != null) {
      currNode.previous.next = currNode.next
    }
    currNode.next = currNode.previous = null
  }

  findLast () {
    let currNode = this.head
    while (currNode.next != null) {
      currNode = currNode.next
    }
    return currNode
  }

  dispReverse () {
    let currNode = this.head
    currNode = this.findLast()
    while (currNode.previous != null) {
      console.log(currNode.element)
      currNode = currNode.previous
    }
  }

//  =======================================
  findN (currNode, n) {
    let nNode = currNode
    while ((n--) > 0) {
      nNode = currNode.previous
    }
    return nNode
  }

  advance (item, n) {
    let currNode = this.find(item)
    let nNode = this.findN(currNode, n)
    this.remove(item)
    this.insert(currNode.element, nNode.previous.element)
  }
}

function print () {
  console.log('=====================')
}

// var cities = new LinkedList()
// cities.insert('Conway', 'head')
// cities.insert('Russellville', 'Conway')
// cities.insert('Carlisle', 'Russellville')
// cities.insert('Alma', 'Carlisle')
// cities.display()
// console.log('===============================')
// cities.advance('Alma', 1)
// cities.display()

var result = [], arr = [1, 2, 3, 4]
var l = arr.length
while (l--) {
  console.log(l)
  result[l] = arr[l]
}
